﻿using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;

public class Client : MonoBehaviour{
    Socket clientSocket;
    byte[] sdata = new byte[1024];
    Thread t;
    // Use this for initialization
    void Start(){
    }

    void ConnectServer(){
        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2234);
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try{
            clientSocket.Connect(ipep);
        }catch (SocketException ex){
            Debug.Log("connect error: " + ex.Message);
            return;
        }

        while (true){
            //接收服务器信息
            int bufLen = 0;
            try{
                bufLen = clientSocket.Available;
                clientSocket.Receive(sdata, 0, bufLen, SocketFlags.None);
                if (bufLen == 0){
                    continue;
                }
            }catch (Exception ex){
                Debug.Log("Receive Error:" + ex.Message);
                return;
            }
            string clientcommand = System.Text.Encoding.UTF8.GetString(sdata).Substring(0, bufLen);
            Debug.Log("客户端收到:" + clientcommand);
            //lstClient.Items.Add(clientcommand);
        }
    }

    void sendMsg(){
        byte[] data = new byte[1024];
        data = Encoding.UTF8.GetBytes(sendStr);
        clientSocket.Send(data, data.Length, SocketFlags.None);
    }

    string sendStr = "Send SomeThing";
    void OnGUI(){
        if (GUILayout.Button("Connect")){
            t = new Thread(new ThreadStart(ConnectServer));
            t.Start();
        }
        sendStr = GUILayout.TextArea(sendStr);
        if (GUILayout.Button("send")){
            sendMsg();
        }
    }

    void OnDestroy(){
		t.Abort();
        if(clientSocket!=null){
            clientSocket.Close();
        }
	}
}
